<?php

use console\db\Migration;
use yii\db\Query;
use yii\db\Expression;
use yii\helpers\ArrayHelper;

/**
 * 创建短视频动态
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m300020_000006_t_sns_dynamic_video_build extends Migration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%sns_dynamic_video}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $query = (new Query())->from($this->tableName);
        $this->handleProgress($query, [$this, 'evenDule']);
    }

    /**
     * @inheritdoc
     */
    public function safeDown() {
        $this->delete('{{%sns_dynamic}}', ['format' => 1]);
        $this->update($this->tableName, ['dynamic_id' => 0]);
    }

    /**
     * 处理结果
     * @param Migration $migration
     * @param array $rows
     */
    public static function evenDule($migration, $rows) {
        $connect = $migration->db->createCommand();
        foreach ($rows as $row) {
            if ($row['deleted_at']) {
                continue;
            }
            $connect->insert('{{%sns_dynamic}}', [
                'user_id' => $row['user_id'],
                'group_id' => 1,
                'format' => 1,
                'status' => 10,
                'created_at' => $row['created_at'],
                'updated_at' => $row['updated_at'],
            ])->execute();
            $connect->update('{{%sns_dynamic_video}}', [
                'dynamic_id' => $migration->db->getLastInsertID('{{%sns_dynamic}}')
            ], ['id' => $row['id']])->execute();
        }
    }

}
